#! usr/lib/python
# coding:utf-8
"""LogServer"""

import time,os,sys

"""日志格式头：时间部分"""
LOG_DATA    =   0
LOG_TIME    =   1
LOG_DATATIME=   2

"""日志格式头：级别部分"""
LOG_DEBUG   =   1
LOG_NOMAL   =   2
LOG_WARING  =   3
LOG_ERROR   =   4

class MLog(object):
    """"""
    def __init__(self,filename):
        """"""
        self.__fmt = 2
        self.__level = 1
        self.__pf = self.__createfile__(filename)
        if not self.__pf:
            raise NameError,"Create log File :'%s' Faild"%filename
    def __createfile__(self,filename):
        """"""
        if not os.path.isfile(filename):
            pf = open(filename,"w")
        else:
            pf = open(filename,"w")

        return pf

    def setformat(self,fmt):
        if fmt in(LOG_DATA,LOG_TIME,LOG_DATATIME):
            self.__fmt = fmt
        else :
            raise NameError,"No type format : \"%s\" for MLog"%fmt

    def setlevel(self,level):
        if level in (LOG_DEBUG,LOG_WARING,LOG_ERROR,LOG_NOMAL):
            self.__level = level
        else :
            raise NameError,"No level :\"%s\" for MLog"%level

    def debug(self,fdata):
        if self.__level > LOG_DEBUG:
            return None
        else :
            tdata = "%s [%s] %s"%(self.__localdata__(),"debug",fdata)
            #print tdata
            print>>self.__pf,tdata
            self.__pf.flush()

    def waring(self,fdata):
        if self.__level >LOG_WARING:
            return None
        else:
            tdata = "%s [%s] %s"%(self.__localdata__(),"waring",fdata)
            #print tdata
            print>>self.__pf,tdata
            self.__pf.flush()

    def error(self,fdata):
        if self.__level >LOG_ERROR:
            return None
        else:
            tdata = "%s [%s] %s"%(self.__localdata__(),"error",fdata)
            #print tdata
            print>>self.__pf,tdata
            self.__pf.flush()

    def nomal(self,fdata):
        if self.__level >LOG_NOMAL:
            return None
        else:
            tdata = "%s [%s] %s"%(self.__localdata__(),"nomal",fdata)
            #print tdata
            print>>self.__pf,tdata
            self.__pf.flush()

    def __localdata__(self):
        """"""
        fmt = ""
        if self.__fmt == LOG_DATA:
            fmt = "%y-%m-%d"
        elif self.__fmt == LOG_TIME:
            fmt = "%H:%M:%S"
        else :
            fmt = "%y-%m-%d %H:%M:%S"
        tm = time.strftime(fmt,time.localtime())
        return tm

if __name__ == "__main__":
    print help(MLog)
    #log = MLog("1.log")
    #log.setformat(2)
    #log.setlevel(1)
    #log.error('123123')